const express = require('express');
const axios = require('axios');
require('dotenv').config();

const router = express.Router();
const BAIDU_MAP_AK = process.env.BAIDU_MAP_AK;

// 地址转坐标接口
router.get('/geocode', async (req, res) => {
    const { address } = req.query;
    if (!address) {
        return res.status(400).json({
            code: 400,
            msg: '缺少address参数'
        });
    }
    try {
        const url = `http://api.map.baidu.com/geocoding/v3/?address=${encodeURIComponent(address)}&output=json&ak=${BAIDU_MAP_AK}`;
        const response = await axios.get(url);
        if (response.data.status === 0){
            res.json({
                code:200,
                location: response.data.result.location
            });
        } else {
            res.status(500).json({
                code: 500,
                msg: response.data.msg
            });
        }
    } catch (err) {
        res.status(500).json({
            code: 500,
            msg: '请求百度地图失败',
            error: err.message
        });
    }
})

module.exports = router;